package com.digitalart.futbol.tld.template;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Pattern;

import javax.servlet.jsp.tagext.BodyTagSupport;

public class SetContentHolder extends BodyTagSupport {
	private static final long serialVersionUID = 1L;

	private String holderId;

	public void setHolderId(String pId) {
		holderId = pId;
	}

	@Override
	public int doStartTag() {

		return EVAL_BODY_BUFFERED;
	}

	

	@Override
	public int doEndTag() {

		String template = getTemplate();
		template = replaceTemplateHolders(template);

		try {
			pageContext.getOut().print(template);
		} catch (IOException e) {
			e.printStackTrace();
		}

		return EVAL_PAGE;
	}

	private String replaceTemplateHolders(String template) {

		
		Pattern p = Pattern.compile("<HOLDER:+[\\w]+/>");
		
		String[] holderParts = p.split(template);
		
		template = holderParts[0] + getBodyContent().getString() +holderParts[1];
		
		return template;
	}

	private String readFile(String template) throws IOException {

		String result = "";
		URL templatePath = new URL(pageContext.getRequest().getScheme() + "://"
				+ pageContext.getRequest().getServerName() + ":"
				+ pageContext.getRequest().getServerPort()
				+ pageContext.getServletContext().getContextPath() + template);

		URLConnection conn;
		conn = templatePath.openConnection();
		BufferedReader bufferedReader = new BufferedReader(
				new InputStreamReader(conn.getInputStream()));
		;
		String inputLine;

		while ((inputLine = bufferedReader.readLine()) != null) {
			
			result += "\n" + inputLine;
		}
		bufferedReader.close();

		return result;
	}

	private String getTemplate() {

		Template tmp = (Template) findAncestorWithClass(this, Template.class);

		String template = "";
		try {
			template = readFile("/template/" + tmp.getTemplateID()
					+ ".template");
		} catch (IOException e) {
			e.printStackTrace();
		}

		return template;
	}
}
